package com.yadong.smarthome2.connections;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Message;

import com.yadong.smarthome2.device.Device;
import com.yadong.smarthome2.protocol2.ResultProtocol.DeviceInfo.DeviceType;

public class ConnectionGarbageCollection {
    private static final int THREAD_IDEL_TIME = 2 * 60 * 1000; //2min
    private static final int THREAD_CHECK_CYCLE = 20 * 1000; //20s
    private ConnectionManager mConnectionManager;
    private HandlerThread mHandlerThread =
            new HandlerThread("ConnectionGarbageCollection");

    public ConnectionGarbageCollection(ConnectionManager connectionManager) {
        this.mConnectionManager = connectionManager;
        mHandlerThread.start();
    }

    public void forceStop() {
        mHandlerThread.quit();
    }

    private Message createEmptyMessage() {
        return mHandler.obtainMessage();
    }

    private Handler mHandler = new Handler(mHandlerThread.getLooper()) {
        public void handleMessage(android.os.Message msg) {
            for (Connection connection : mConnectionManager.getConnections()) {
                Device device = connection.getDevice();
                //Control device will not force disconnect
                if (device.getDeviceType() == DeviceType.CONTROL) {
                    continue;
                }
                long currentTime = System.currentTimeMillis();
                if (currentTime - connection.getLastActive() > THREAD_IDEL_TIME) {
                    mConnectionManager.forceDisConnect(connection.getDevice());
                }
            }
            mHandler.sendMessageDelayed(createEmptyMessage(), THREAD_CHECK_CYCLE);
        };
    };

    public void start() {
        createEmptyMessage().sendToTarget();
    }

}
